package com.ems.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ems.dao.*;
import com.ems.dto.Score;
import com.ems.dto.StudentPaper;
import com.ems.entity.*;
import com.ems.service.StudentService;
import com.ems.utils.MyUtils;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    ExamPaperQuAnswerDao examPaperQuAnswerDao;

    @Autowired
    ExamPaperQuDao examPaperQuDao;

    @Autowired
    ExamDao examDao;

    @Autowired
    StuExamDao stuExamDao;

    @Autowired
    StudentDao studentDao;

    @Autowired
    MyDtoMapper myDtoMapper;

    @Autowired
    ExamPaperDao examPaperDao;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static public class QA{
        private Integer pqid;
        private Integer qaid;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static public class MuQA{
        private Integer pqid;
        private ArrayList<Integer> qaid;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static public class SubQA{
        private Integer pqid;
        private String answer;
    }
    @Override
    //1.20王
    public List<Exam> exam(Integer stuid) {
        //先查询到所有的考试id
        List<Integer> list = stuExamDao.eidBystuid(stuid);
        if (list.isEmpty()) return null;
        //再查询集合里id对应的所有数据
        return examDao.queryAllByEid(list);
    }

    @Override
    //1.22王
    public Score score(Integer stuid){
        //先查询所有的考试id

        return myDtoMapper.score(stuid);
    }

    @Override
    public boolean register(JSONObject jsonObject) {
        Student student = new Student();

        //先获取data对象，不然无法直接获取下面的key-value（可能有啥能直接获取的）
        JSONObject json = jsonObject.getJSONObject("data");
        student.setPhone(json.getString("phone"));
        student.setPassword(json.getString("password"));
        student.setAcademy(json.getString("academy"));
        student.setSpecialty(json.getString("specialty"));
        student.setClassName(json.getString("className"));
        student.setUsername(json.getString("username"));
        student.setWechat(json.getString("wechat"));
        student.setName(json.getString("name"));
        student.setAge(json.getInteger("age"));
        student.setSex(json.getInteger("sex"));
        student.setEmail(json.getString("email"));

        return studentDao.insert(student) != 0;
    }

    @Override
    public StudentPaper getExamPaper(Integer eid, Integer uid) {
        return myDtoMapper.studentGetExamPaper(eid, uid);
    }

    @Override

    public boolean putAnswer(JSONObject jsonObject) {
        ExamPaperQu examPaperQu = new ExamPaperQu();
        //获取考生的答案
        JSONObject json = jsonObject.getJSONObject("data");
        Integer pid = json.getInteger("pid");
        Integer eid = json.getInteger("eid");
        Integer stuid = json.getInteger("stuid");
        //检查是否已经提交过
        int isFinish = stuExamDao.queryIsFinish(eid, stuid);
        int id = stuExamDao.queryIDByeid_stuid(eid, stuid);
        if(isFinish == 1) return false;

        ArrayList singleChoice = json.getObject("singleChoice", ArrayList.class);
        ArrayList multipleChoice = json.getObject("multipleChoice", ArrayList.class);
        ArrayList subjectiveQuestions = json.getObject("subjectiveQuestions", ArrayList.class);

        Iterator Site = singleChoice.iterator();
        Iterator Mite = multipleChoice.iterator();
        Iterator SUBite = subjectiveQuestions.iterator();


        while(Site.hasNext()){
            String jsonString = JSON.toJSONString(Site.next());
            QA qa = JSONObject.parseObject(jsonString, QA.class);

            ExamPaperQu paperQu = new ExamPaperQu();
            paperQu.setId(qa.pqid);
            paperQu.setAnswered(1);

            //修改是否回答
            examPaperQuAnswerDao.updateChecked(qa.getQaid());
            //检查答案是否正确
            Integer isRight = examPaperQuAnswerDao.queryIsRight(qa.getQaid());
            if (isRight == null)
            {
                paperQu.setIsRight(0);
                paperQu.setActualScore(0);
            }
            else if (isRight == 1)
            {
                paperQu.setIsRight(1);
                ExamPaperQu qu = examPaperQuDao.queryById(qa.pqid);
                paperQu.setActualScore(qu.getScore());
            }
            else {
                paperQu.setIsRight(0);
                paperQu.setActualScore(0);
            }
            examPaperQuDao.update(paperQu);

        }
        while(Mite.hasNext()){
            String jsonString = JSON.toJSONString(Mite.next());
            MuQA qa = JSONObject.parseObject(jsonString, MuQA.class);

            ExamPaperQu paperQu = new ExamPaperQu();
            paperQu.setId(qa.pqid);
            paperQu.setAnswered(1);

            //修改答案
            //改为已经回答了
            examPaperQuDao.updateAnswered(qa.getPqid());
            List<Integer> Qaid_list = qa.getQaid();
            System.out.println("多选题的选项id：" + Qaid_list);
            //检查答案是否正确
            List<Integer> Qaid_all = examPaperQuAnswerDao.queryIsRightAll(pid, qa.pqid);
            System.out.println("实际所有选型：" + Qaid_all);

            if (Qaid_all.size() == 0)
            {
                paperQu.setIsRight(0);
                paperQu.setActualScore(0);
            }

            else if (MyUtils.equalsArrayListInteger(Qaid_list,Qaid_all))
            {
                paperQu.setIsRight(1);
                ExamPaperQu qu = examPaperQuDao.queryById(qa.pqid);
                paperQu.setActualScore(qu.getScore());
            }
            else{
                paperQu.setIsRight(0);
                paperQu.setActualScore(0);
            }
            //更新答案
            for(Integer i : Qaid_list){
                examPaperQuAnswerDao.updateChecked(i);
            }
            examPaperQuDao.update(paperQu);

        }
        while(SUBite.hasNext()){
            String jsonString = JSON.toJSONString(SUBite.next());
            SubQA qa = JSONObject.parseObject(jsonString, SubQA.class);
            examPaperQu.setAnswer(qa.getAnswer());
            examPaperQu.setQuId(qa.getPqid());
            examPaperQu.setAnswered(1);
            examPaperQuDao.updateAnswer(examPaperQu);
        }

        //修改 学生修改试卷的时间
        ExamPaper examPaper = new ExamPaper();
        examPaper.setId(pid);
        examPaper.setUpdateTime(new Date());
        examPaperDao.update(examPaper);

        //修改提交状态
        StuExam stuExam = new StuExam();
        stuExam.setIsfinish(1);
        stuExam.setEid(eid);
        stuExam.setIsjoin(1);
        stuExam.setStuid(stuid);
        stuExam.setId(id);
        stuExamDao.update(stuExam);

        return true;
    }

    @Override
    public Student queryByUsername(String username) {
        return studentDao.queryByUsername(username);
    }
}
